package com.ant.collect.service.impl;

import com.ant.collect.dto.MaterialDto;
import com.ant.collect.mapper.MaterialMapper;
import com.ant.collect.mapper.MaterialProductMapper;
import com.ant.collect.pojo.Company;
import com.ant.collect.pojo.Material;
import com.ant.collect.pojo.MaterialProduct;
import com.ant.collect.service.IMaterialService;
import com.ant.collect.service.IUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hzd
 * @since 2025-10-31
 */
@Service
public class MaterialServiceImpl extends ServiceImpl<MaterialMapper, Material> implements IMaterialService {

    private static final Logger logger = LoggerFactory.getLogger(MaterialServiceImpl.class);
    @Resource
    MaterialProductMapper productMapper;

    @Autowired
    IUserService userService;

    private static final int REVIEW_STATUS_ACTIVE = 1;

    @Override
    public List<Material> listById(Integer id) {
        List<Material> list = baseMapper.selectList(new QueryWrapper<Material>().eq("company_id", id));
        list.stream().forEach(item -> {
            item.setProductList(productMapper.selectList(new QueryWrapper<MaterialProduct>().eq("parent_id", item.getId())));
        });
        return list;
    }

    @Override
    public Material saveMaterial(MaterialDto dto) {
        try {
            if (dto == null) {
                throw new IllegalArgumentException("DTO对象不能为空");
            }
            Material year = new Material();
            year.setIndustry(dto.getIndustry());
            year.setCompanyId(dto.getCompanyId());
            year.setAccessoryName(dto.getAccessoryName());
            if (dto != null) {
                year.setManufacturer(dto.getManufacturer());
            }
            year.setManufacturerTel(dto.getManufacturerTel());
            year.setAccessoryCategory(dto.getAccessoryCategory());
            year.setAccessoryNature(dto.getAccessoryNature());
            year.setAccessoryAgency(dto.getAccessoryAgency());
            year.setAccessoryKind(dto.getAccessoryKind());
            year.setAccessoryType(dto.getAccessoryType());
            if (dto != null) {
                year.setVocUrl(dto.getVocUrl());
            }
            // 或者使用枚举方式
            year.setReview(REVIEW_STATUS_ACTIVE);
            year.setCreationTime(LocalDateTime.now());
            if (dto.getId() == null) {
                baseMapper.insert(year);
            } else {
                year.setId(dto.getId());
                baseMapper.updateById(year);
            }
            return year;
        } catch (Exception e) {
            logger.error("保存材料信息失败", e);
            throw new RuntimeException("保存材料信息失败", e);
        }

    }

    @Override
    public Map<String, Object> queryPageList(MaterialDto dto) {
        try {
            Page<Material> pageInfo = new Page<Material>(
                    dto != null && dto.getPageIndex() > 0 ? dto.getPageIndex() : 1,
                    dto != null && dto.getPageSize() > 0 ? dto.getPageSize() : 10
            );

            QueryWrapper<Material> wrapper = new QueryWrapper<>();

            if (!ObjectUtils.isEmpty(dto.getAccessoryName())) {
                wrapper.eq("accessory_name", dto.getAccessoryName());
            }
            if (!ObjectUtils.isEmpty(dto.getCompanyId())) {
                wrapper.eq("company_id", dto.getCompanyId());
            }

            Page<Material> userPage = baseMapper.selectPage(pageInfo, wrapper);
            List<Material> list = userPage.getRecords();
            list.stream().forEach(item -> {

                List<MaterialProduct> tal =
                        productMapper.selectList(new QueryWrapper<MaterialProduct>()
                                .eq("parent_id", item.getId()));
                item.setProductList(tal);
            });
            Map<String, Object> map = new HashMap<>();
            map.put("list", list);
            map.put("total", userPage.getTotal());
            return map;
        } catch (Exception e) {
            logger.error("查询材料列表失败", e);
            throw new RuntimeException("查询材料列表失败", e);
        }
    }

    @Override
    public Map<String, Object> findListCompanyIdPage(MaterialDto dto) {
        try {
            Company company = userService.getUserCompanyId();
            Page<Material> pageInfo = new Page<Material>(dto.getPageIndex(), dto.getPageSize());
            QueryWrapper<Material> wrapper = new QueryWrapper<>();
            if (!ObjectUtils.isEmpty(dto.getAccessoryName())) {
                wrapper.eq("accessory_name", dto.getAccessoryName());
            }
            if (company != null) {
                wrapper.eq("company_id", company.getId());
            }
            wrapper.eq("review", 2);
            wrapper.orderByDesc("id");
            Page<Material> userPage = baseMapper.selectPage(pageInfo, wrapper);
            Map<String, Object> map = new HashMap<>();
            map.put("list", userPage.getRecords());
            map.put("total", userPage.getTotal());
            return map;
        } catch (Exception e) {
            logger.error("查询材料列表失败", e);
            throw new RuntimeException("查询材料列表失败", e);
        }

    }

    @Override
    public void findApproved(Integer id, Integer status) {
        // 参数校验
        if (id == null || id <= 0) {
            throw new IllegalArgumentException("无效的材料ID");
        }
        if (status == null) {
            throw new IllegalArgumentException("审核状态不能为空");
        }
        Material material = new Material();
        material.setId(id);
        material.setReview(status);
        try {
            baseMapper.updateById(material);
        } catch (Exception e) {
            // 记录日志或进行其他异常处理
            logger.error("更新材料审核状态失败，材料ID: {}, 状态: {}", id, status, e);
            throw new RuntimeException("更新材料审核状态失败", e);
        }

    }

    @Override
    public Material findMaterialDetails(Integer id) {
        if (id == null) {
            throw new IllegalArgumentException("无效的材料ID");
        }
        try {
            Material selectOne = baseMapper.selectOne(new QueryWrapper<Material>().eq("id", id));
            List<MaterialProduct> tal = productMapper.selectList(new QueryWrapper<MaterialProduct>()
                    .eq("parent_id", id));
            selectOne.setProductList(tal);
            return selectOne;
        } catch (Exception e) {
            logger.error("查询材料详情失败", e);
            throw new RuntimeException("查询材料详情失败", e);
        }
    }
}
